import { BaseContext } from "koa";
import { getRepository } from "typeorm";
import authorize from "../../middleware/authorize";
import { Get, Post, Controller } from "../../middleware/request";
import { Exception } from "../../utils/exception";
import { Carousel } from "../entity/Carousel";
import { auth as Auth } from "../../utils/auth";
import { encrypt, decrypt } from "../../utils/crypto";
@Controller("/api/carousel")
export class CarouselController {
	@Get("/list")
	async getCarousel(ctx: BaseContext) {
		try {
			const carouselRepository = getRepository(Carousel)
			const carousels = await carouselRepository.find({
				order: {
					carousel_id: "DESC",
				}
			})
			ctx.body = {
				...Exception(200, "查询成功"),
				data: carousels
			}
		} catch (error) {
			ctx.body = Exception(112, "查询失败");
		}
	}

	@Post('/add')
	async addCarousel(ctx: BaseContext) {
		try {
			const carouselRepository = getRepository(Carousel)
			// const { imgPath, status ,describes,product_id} = ctx.request.body;
			const data = ctx.request.body;
			let carousel = new Carousel()
			carousel = data
			await carouselRepository.save(carousel)
			ctx.body = Exception(200, "添加成功");
		} catch (error) {
			ctx.body = Exception(112, "添加失败");
		}
	}


	@Post('/update')
	async updateCarousel(ctx: BaseContext) {
		try {
			const { carousel_id, status } = ctx.request.body;
			if (!carousel_id) {
				return ctx.body = Exception(112, "id不能为空")
			}
			const carouselRepository = getRepository(Carousel)
			const carousels = await carouselRepository.findOne(carousel_id)
			if (!carousels) return ctx.body = Exception(112, "id不存在");
			carousels.status = status
			await carouselRepository.save(carousels)
			ctx.body = Exception(200, "更新成功");
		} catch (error) {
			ctx.body = Exception(112, "更新失败");
		}
	}


	@Post('/del')
	async delCarousel(ctx: BaseContext) {
		try {
			const { id } = ctx.request.body;
			if (!id) {
				return ctx.body = Exception(112, "id不能为空")
			}
			const carouselRepository = getRepository(Carousel)
			const carousels = await carouselRepository.findOne(id)
			if (!carousels) return ctx.body = Exception(112, "id不存在");
			await carouselRepository.remove(carousels)
			ctx.body = Exception(200, "删除成功");
		} catch (error) {
			ctx.body = Exception(112, "删除失败");
		}
	}
}
